package com.bstek.demo.service.impl;

import java.util.Collection;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.bstek.demo.dao.DeptDao;
import com.bstek.demo.entity.Dept;
import com.bstek.demo.entity.User;
import com.bstek.demo.service.DeptService;
import com.bstek.dorado.data.entity.EntityState;
import com.bstek.dorado.data.entity.EntityUtils;
/**
 * 部门信息实现类
 * @author lemon
 *
 */
@Service
public class DeptServiceImpl implements DeptService{
	
	@Autowired DeptDao deptDao;
	

	/**
	 * 获取顶层部门信息
	 */
	@Override
	public Collection<Dept> getTopDept() {
		Collection<Dept> deptSet = deptDao.getTopDept();
		return getChildren(deptSet);
	}

	/**
	 * 递归获取子部门信息
	 * @author lemon
	 * @param deptSet
	 * @return 返回子部门信息
	 */
	public Collection<Dept> getChildren(Collection<Dept> deptSet){
		for(Dept dept : deptSet){
			Set<Dept> deptset = deptDao.getChildrenDept(dept.getDeptid());
			if(deptset.size() != 0){
				dept.setDeptSet(deptset);
				getChildren(deptset);
			}else{
				dept.setDeptSet(deptset);
			}
		}
		return deptSet;
	}

	/**
	 * 获取子部门信息 根据父部门id
	 */
	@Override
	public Collection<Dept> getChildrenDeptByDeptId(Integer deptid) {
		Collection<Dept> dept = null; 
		if(deptid != null){
			dept = deptDao.getChildrenDept(deptid);
		}
		return dept;
	}

	/**
	 * 保存部门信息
	 */
	@SuppressWarnings({ "unchecked", "unused" })
	@Override
	@Transactional
	public void saveAll(Collection<Dept> depts) {
		for(Dept dept : depts){
			// 获取状态
			EntityState state = EntityUtils.getState(dept);
			System.out.println(state);
		}
	}
	/**
	 * 递归获取最底层部门信息
	 * @param dept
	 * @return 
	 */
	public Dept getChild(Dept dept){ 
		Set<Dept> depts = dept.getDeptSet();
		if( depts != null){
			for(Dept d : depts){
				return getChild(d);
			}
		}
		return dept;
	}
	
	
}
